const { login } = require('../controller/user');
const { set } = require('../db/redis');
const { SuccessModel, ErrorModel } = require('../model/resModel');

const handleUserRouter = (req, res) => {
  const method = req.method;
  const url = req.url;
  const path = url.split('?')[0];

  if(method === 'POST' && path === '/api/user/login'){
    const { username, password } = req.payload;
    const result = login(username, password)

    return result.then(user => {
      if(user.username) {
        req.session.username = user.username;
        req.session.realname = user.realname;
        set(req.sessionId, req.session);
        return new SuccessModel(user, '登陆成功！');
      }
      return new ErrorModel(user, '登陆失败！');
    })
  }
}

module.exports = handleUserRouter;
